import re
import time

from PageObjectRequests import base_url
from util import http_utils
from util.g import g
from util.inform.sendEmail import sendEmail
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import FormDataDecorator

# # # # # # # #        填写申请书封皮             completed                # # # # # # # # # # #


class WriteApplicationCover():
    token = ""
    form_btn_loc = (By.LINK_TEXT, '申请书封皮')
    # form_btn_loc = (By.XPATH, '//a[contains(text(), "申请书封皮")]')
    title_loc = (By.CSS_SELECTOR, 'h2.text-center')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    # cercification_body 认定机构
    cer_body_select_loc = (By.CSS_SELECTOR, 'select#centersAuthorized')
    # application_date

    application_date_loc = (By.CSS_SELECTOR, 'input#hadate')
    date_js_str = "document.getElementById('hadate').removeAttribute('readonly')"
    save_btn_loc = (By.CSS_SELECTOR, 'button#saver.green')
    print_btn_loc = (By.CSS_SELECTOR, 'button#print')

    # 写代码时方便提示, 基本方法完成后删除
    # driver = driver
    def __init__(self, driver=None):
        self.driver = driver

    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, cert_org='', app_date=''):
        try:
            # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
            ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
            detail_url = ele.get_attribute("href")
            if not g.all_optimized:
                BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
            BM.get_cookie(driver=self.driver)
            detail_url = detail_url if detail_url.startswith("https://") else \
                base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            res = http_utils.send_get(detail_url, driver=self.driver)
            text = res.get("text")
            token = res.get("token")
            self.token = token
            url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveDataWrappage.do"

            data = {
                "dataInnocom.id": "",
                "struts.token.name": "token",
                "token": token,
                "dataInnocom.deptOffice": cert_org,
                "dataInnocom.reportDate": app_date
            }

            data_innocom_id_pattern = '.*?name="dataInnocom.id".*?.value="(.*?)".*?'
            data_innocom_id_res = re.findall(data_innocom_id_pattern, text, re.S)
            data["dataInnocom.id"] = "".join(data_innocom_id_res)

            result = http_utils.send_post(url, data=data, driver=self.driver)
            text = result.get("text")
            message = result.get("message")
            g.logger.info("申请书封皮上传结果: {}".format(message))
            token = result.get("token")
            self.token = token

            if u"成功" in message:
                return True
            else:
                content = "{}-{}---{}--{}".format(g.entname, g.co_id, "申请书封皮", message)
                a = sendEmail(subject="autoflow", content=content, target="18235693860@163.com")
                a.send_mail()
                return False
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
